package com.sicurezza.nfcrypto;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Fragment;
import android.content.ContentResolver;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.util.Base64;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.progettoSicurezza.secUtility.KeySaver;

public class ContactPickerActivity extends Activity {
	
	private byte[] key;
	private byte[] salt;
	private static final int PICK_CONTACT=1;
	private static final String TAG = "ContactPickerActivity";
	private String id;
	private String name;
	private String phoneNumber;
	private String choosenEmail;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_contact_picker);

		if (savedInstanceState == null) {
			getFragmentManager().beginTransaction()
					.add(R.id.container, new PlaceholderFragment()).commit();
		}
		salt = KeySaver.saltGenerator();
		Intent caller = this.getIntent();
		this.key = caller.getByteArrayExtra("encodedKey");
		
		Intent contactPickIntent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
		startActivityForResult(contactPickIntent, PICK_CONTACT);
		
		Button saveButton = (Button) findViewById(R.id.buttonSave);
		saveButton.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				Log.v(TAG, "Salvataggio contatto sul Database");
				KeySaver.saveKey(getApplicationContext(), key, id);
				String hash = KeySaver.returnKeyAsHash(key, salt, "SHA-256", getApplicationContext());
				String saltString = Base64.encodeToString(salt, Base64.DEFAULT);
				Intent updateDbIntent = new Intent(getApplicationContext(), DbUpdater.class);
				updateDbIntent.putExtra(DbUpdater.CONTACT_ID, id);
				updateDbIntent.putExtra(DbUpdater.CONTACT_DISPLAY_NAME, name);
				updateDbIntent.putExtra(DbUpdater.CONTACT_PHONE_NUMBER, phoneNumber);
				updateDbIntent.putExtra(DbUpdater.CONTACT_EMAIL_ADDRESS, choosenEmail);
				updateDbIntent.putExtra(DbUpdater.SALT_STRING_VALUE, saltString);
				updateDbIntent.putExtra(DbUpdater.KEY_HASH_VALUE, hash);
				startService(updateDbIntent);
				finish();
				
			}
		});
		
		Button modifyButton = (Button) findViewById(R.id.buttonModify);
		modifyButton.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				
				Intent contactPickIntent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
				startActivityForResult(contactPickIntent, PICK_CONTACT);
				
			}
		});
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		
		if(requestCode == PICK_CONTACT && resultCode == Activity.RESULT_OK){
			Uri contactUri = data.getData();
			Log.v(TAG, "Trovato il contatto");
			ContentResolver cr = this.getContentResolver();
			id = contactUri.getLastPathSegment();
			Cursor c = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + "=?", new String[]{id}, null);
			Cursor c2 = cr.query(ContactsContract.CommonDataKinds.Email.CONTENT_URI, null, ContactsContract.CommonDataKinds.Email.CONTACT_ID + "=?", new String[]{id}, null);
			int phoneIndex = c.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
			int phoneType = c.getColumnIndex(ContactsContract.CommonDataKinds.Phone.TYPE);
			int emailIndex = c2.getColumnIndex(ContactsContract.CommonDataKinds.Email.ADDRESS);
			int emailType = c2.getColumnIndex(ContactsContract.CommonDataKinds.Email.TYPE);
			name = c.getString(c.getColumnIndex(Phone.DISPLAY_NAME));
			
			if(c.getCount() > 1){
				final CharSequence[] numbers = new CharSequence[c.getCount()];
				int i = 0;
				if(c.moveToFirst()){
					while(!c.isAfterLast()){
						String type = (String) ContactsContract.CommonDataKinds.Phone.getTypeLabel(getResources(), phoneType, "");
						String numero = type + ": " + c.getString(phoneIndex); 
						numbers[i++] = numero;
						c.moveToNext();
					}
					
					AlertDialog.Builder adb = new AlertDialog.Builder(this);
					adb.setTitle(R.string.select_multiple_numbers);
					adb.setItems(numbers, new DialogInterface.OnClickListener() {
						
						@Override
						public void onClick(DialogInterface dialog, int which) {
							String number = (String) numbers[which];
			                int index = number.indexOf(":");
			                number = number.substring(index + 2);
			                saveDetail(detailsEnum.NUMBER,number);
			                Log.v(TAG, "Scelto e preso il numero di telefono");
						}
					});
					AlertDialog alert = adb.create();
					alert.setOwnerActivity(this);
					alert.show();
				}
				else Log.w(TAG, "No more result");
			}
			else if (c.getCount() == 1){
				if(c.moveToFirst()){
					this.phoneNumber = c.getString(phoneIndex);
					Log.v(TAG, "Preso numero di telefono");
				}
			}
			if(c2.getCount() > 1){
				final CharSequence[] mails = new CharSequence[c2.getCount()];
				int i = 0;
				if(c2.moveToNext()){
					while(!c2.isAfterLast()){
						String type = (String) ContactsContract.CommonDataKinds.Email.getTypeLabel(getResources(), emailType, "");
						String mail = type + ": " + c2.getString(emailIndex);
						mails[i++] = mail;
					}
					AlertDialog.Builder adbm = new AlertDialog.Builder(this);
					adbm.setTitle(R.string.select_multiple_mail);
					adbm.setItems(mails, new DialogInterface.OnClickListener() {
						
						@Override
						public void onClick(DialogInterface dialog, int which) {
							String mail = (String) mails[which];
			                int index = mail.indexOf(":");
			                mail = mail.substring(index + 2);
			                saveDetail(detailsEnum.NUMBER,mail);
			                Log.v(TAG, "Scelto e presa la mail");
						}
					});
					AlertDialog alertMail = adbm.create();
					alertMail.setOwnerActivity(this);
					alertMail.show();
				}
				else Log.w(TAG, "No more result");
			}
			else if(c2.getCount() == 1){
				if(c2.moveToFirst()){
					 this.choosenEmail = c2.getString(emailIndex);
					 Log.v(TAG, "Presa la mail");
				}
			}
		}
		
		TextView nameView = (TextView) findViewById(R.id.textName);
		nameView.setText(name);
		
		EditText phoneEditText = (EditText) findViewById(R.id.editTextPhoneNumber);
		phoneEditText.setText(phoneNumber);
		
		EditText mailEditText = (EditText) findViewById(R.id.editTextMailAddress);
		mailEditText.setText(choosenEmail);
		
		EditText hashEditText = (EditText) findViewById(R.id.editTextHash);
		hashEditText.setText(KeySaver.returnKeyAsHash(key, salt, "SHA-256", this));
		
		EditText saltEditText = (EditText) findViewById(R.id.editTextSalt);
		saltEditText.setText(Base64.encodeToString(salt, Base64.DEFAULT));
		
	}

	protected void saveDetail(detailsEnum det, String detail){
		switch(det){
		case NUMBER:
			this.phoneNumber = detail;
			break;
		case MAIL:
			this.choosenEmail = detail;
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {

		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.contact_picker, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		int id = item.getItemId();
		if (id == R.id.action_settings) {
			return true;
		}
		return super.onOptionsItemSelected(item);
	}

	/**
	 * A placeholder fragment containing a simple view.
	 */
	public static class PlaceholderFragment extends Fragment {

		public PlaceholderFragment() {
		}

		@Override
		public View onCreateView(LayoutInflater inflater, ViewGroup container,
				Bundle savedInstanceState) {
			View rootView = inflater.inflate(R.layout.fragment_contact_picker,
					container, false);
			return rootView;
		}
	}

}

enum detailsEnum{
	NUMBER,
	MAIL
}
